package com.cai.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration  // 代替之前的bean.xml
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    // 后台监控 相当于 web.xml 利用ServletRegistrationBean代替
    @Bean
    public ServletRegistrationBean StatViewServlet() {
        // 固定写法
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        HashMap<String, String> initParameters = new HashMap<>();
        // 增加配置 登录参数key固定的 不能自定义
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");

        // 允许是谁访问 （第一个参数allow，第二个参数为空代表所有人都可以访问）
        initParameters.put("allow", "");

        // 禁止谁访问 禁止指定ip访问
//        initParameters.put("zhang_san","192.168.11.123");

        bean.setInitParameters(initParameters); // 设置初始化参数
        return bean;
    }

    // filter 过滤器
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParameters = new HashMap<>();
        // 过滤请求 exclusions排除
        initParameters.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }

}
